#!/usr/bin/php
<?php

function main($argc, & $argv)
{
    $sd = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
    if (!$sd) {
        echo socket_strerror(socket_last_error($sd)), PHP_EOL;
        return 0;
    }

    socket_connect($sd, "3.3.3.9", 80);

    if ($argc < 2)
        $filename = "";
    else
        $filename = $argv[1];

    $s = "GET /".$filename." HTTP/1.1\r\n";
    $s .= "Host:3.3.3.9\r\n\r\n";
    $ret = socket_write($sd, $s, strlen($s));
    echo "send: ", $ret, PHP_EOL;

    $s = socket_read($sd, 1024);
    echo $s, PHP_EOL;

    $file = "";
    while (1) {
        $s = socket_read($sd, 1024);
        $len = strlen($s);
        $file .= $s;
        if ($len < 1024)
            break;
    }

    file_put_contents("./http.down", $file);

    socket_close($sd);

    return 0;
}

exit(main($argc, $argv));

